<?php
/**
 * System_Model_RoleMapper
 *
 * @author mmxie
 * @copyright Copyright (c) 2009 Green Shore (http://www.iwgame.com)
 * @version $Id: RoleMapper.php 906 2011-10-20 02:38:33Z mmxie $
 */
class System_Model_RoleMapper extends IG_ModelMapper
{
    /**
     * Fetch all model
     *
     * @param string|array $where
     * @param string|array $order
     * @param int $limit
     * @param int $offset
     * @return array
     */
    public function getResources()
    {
        return $this->getDbTable()->getResources($this->getModel());
    }

    /**
     *
     * @param System_Model_Role $role
     * @return array
     */
    public function findResource($role)
    {
        $rowset = $this->getDbTable()->find($role->getRoleId());
        $resultSet = $rowset->current()
            ->findManyToManyRowset('System_Model_DbTable_Resource', 'System_Model_DbTable_RoleResource');
        $resources = array();
        foreach ($resultSet as $row) {
            $resource = new System_Model_Resource();
            $resource->setResourceId($row->resource_id)
                ->setEmployee($row->employee)
                ->setModule($row->module)
                ->setController($row->controller)
                ->setAction($row->action)
                ->setAtime($row->atime)
                ->setName($row->name)
                ->setParam($row->param);
            $resources[] = $resource;
        }
        return $resources;
    }

    private $_dbRoleResource;

    public function saveResource(System_Model_Role $role, array $resources)
    {
        $dbRoleResource = $this->getRoleResourceDbTable();

        $dbRoleResource->delete(array('role_id=?' => $role->getRoleId()));

        foreach ($resources as $id) {
            $dbRoleResource->insert(array('role_id' => $role->getRoleId(), 'resource_id' => $id));
        }
    }

    public function getResourceIds($roleId)
    {
        return $this->getRoleResourceDbTable()->getResourceIds($roleId);
    }

    /**
     * @return System_Model_DbTable_RoleResource
     */
    public function getRoleResourceDbTable() {
        if ($this->_dbRoleResource === null) {
            $this->_dbRoleResource = new System_Model_DbTable_RoleResource();;
        }
        return $this->_dbRoleResource;
    }
}

